package com.quan.commons.core.utils;

import com.google.zxing.Reader;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.*;

/**
 * 二维码工具类
 * @作者：杨浩泉 @日期：2016年10月4日
 */
public class ZXingUtils {

    public static enum ImageType {
        JPEG("jpeg"), PNG("png"), GIF("gif");
        private String value;

        ImageType(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    /**
     * 编码
     */
    public static class Encode {

        private static Map<EncodeHintType, Object> HINTS;

        static {
            HINTS = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
            HINTS.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        }

        /**
         * 生成二维码
         * @param widthAndHeight 高宽
         * @param content        二维码内容
         * @param os             输出流
         */
        public static void buildQRCode(int widthAndHeight, String content, OutputStream os, ImageType imageType, boolean deleteWhite)
                throws WriterException, IOException {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthAndHeight,
                    widthAndHeight, HINTS);// 生成矩阵

            //去除白边
            if (deleteWhite) {
                bitMatrix = deleteWhite(bitMatrix);
            }
            MatrixToImageWriter.writeToStream(bitMatrix, imageType.getValue(), os);
        }

        public static void buildQRCode(String content, OutputStream os, ImageType imageType)
                throws WriterException, IOException {
            buildQRCode(200, content, os, imageType, false);
        }

        /**
         * 生成二维码
         * @param widthAndHeight 高宽
         * @param content        二维码内容
         * @param filePath       输出目录
         * @param fileName       输出文件名
         * @param imageType      输出文件类型
         */
        public static void buildQRCode(int widthAndHeight, String content, String filePath, String fileName,
                                       ImageType imageType) throws WriterException, IOException {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthAndHeight,
                    widthAndHeight, HINTS);
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, imageType.getValue(), path);// 输出图像
        }

        public static void buildQRCode(String content, String filePath, String fileName, ImageType imageType)
                throws WriterException, IOException {
            buildQRCode(200, content, filePath, fileName, imageType);
        }

        /**
         * 生成二维码
         * @param content     内容
         * @param width       宽度
         * @param height      高度
         * @param deleteWhite 是否去除白边
         * @return
         * @throws WriterException
         * @throws IOException
         */
        public static BufferedImage genBarcode(String content, int width, int height, boolean deleteWhite)
                throws WriterException, IOException {
            // 读取源图像
            Map<EncodeHintType, Object> hint = new HashMap<>();
            hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hint.put(EncodeHintType.MARGIN, 1);
            // 生成二维码
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hint);
            // 去除白边
            if (deleteWhite) {
                matrix = deleteWhite(matrix);
            }
            BufferedImage image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < matrix.getWidth(); x++) {
                for (int y = 0; y < matrix.getHeight(); y++) {
                    image.setRGB(x, y, matrix.get(x, y) ? 0 : 255);
                }
            }
            return MatrixToImageWriter.toBufferedImage(matrix);
        }

        /**
         * 生成二维码，不去除白边
         * @param content 内容
         * @param width   宽度
         * @param height  高度
         * @return
         * @throws WriterException
         * @throws IOException
         */
        public static BufferedImage genBarcode(String content, int width, int height)
                throws WriterException, IOException {
            return genBarcode(content, width, height, false);
        }

        /**
         * 将二维码转换成字节
         * @param image
         * @return
         * @throws IOException
         */
        public static byte[] imageToByte(BufferedImage image) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image, "png", out);
            byte[] b = out.toByteArray();
            out.close();
            return b;
        }

        // 去除白边
        private static BitMatrix deleteWhite(BitMatrix matrix) {
            int[] rec = matrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;

            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++) {
                for (int j = 0; j < resHeight; j++) {
                    if (matrix.get(i + rec[0], j + rec[1]))
                        resMatrix.set(i, j);
                }
            }
            return resMatrix;
        }
    }

    /**
     * 解码
     */
    public static class Decode {

        private static final Map<DecodeHintType, Object> HINTS;
        private static final Map<DecodeHintType, Object> HINTS_PURE;

        static {
            HINTS = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
            HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
            HINTS_PURE = new EnumMap<DecodeHintType, Object>(HINTS);
            HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        }

        /**
         * 解析二维码
         */
        public static Collection<Result> readQRCode(File qrCode) throws ReaderException, IOException {
            FileInputStream inputStream = new FileInputStream(qrCode);
            return readQRCode(inputStream);
        }

        public static Collection<Result> readQRCode(InputStream inputStream) throws ReaderException, IOException {
            LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(inputStream));
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            Collection<Result> results = new ArrayList<Result>(1);
            ReaderException savedException = null;
            Reader reader = new MultiFormatReader();
            try {
                // 寻找多个条码
                MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
                Result[] theResults = multiReader.decodeMultiple(binaryBitmap, HINTS);
                if (theResults != null) {
                    results.addAll(Arrays.asList(theResults));
                }
            } catch (ReaderException re) {
                savedException = re;
            }

            if (results.isEmpty()) {
                try {
                    // 寻找纯条码
                    Result theResult = reader.decode(binaryBitmap, HINTS_PURE);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }

            if (results.isEmpty()) {
                try {
                    // 寻找图片中的正常条码
                    Result theResult = reader.decode(binaryBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }

            if (results.isEmpty()) {
                try {
                    // 再次尝试其他特殊处理
                    BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result theResult = reader.decode(hybridBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()) {
                throw savedException;
            } else {
                return results;
            }
        }

        public static Result readQRCodeResult(File qrCode) throws ReaderException, IOException {
            FileInputStream inputStream = new FileInputStream(qrCode);
            return readQRCodeResult(inputStream);
        }

        public static Result readQRCodeResult(InputStream inputStream) throws ReaderException, IOException {
            Collection<Result> results = readQRCode(inputStream);
            if (!results.isEmpty()) {
                // 寻找结果集中非空的结果
                for (Result result : results) {
                    if (result != null) {
                        return result;
                    }
                }
            }
            throw NotFoundException.getNotFoundInstance();
        }
    }

    public static void main(String[] args) {
        try {
            String content = "Hello Gem, welcome to Zxing!" + "\nBlog [ http://castte.iteye.com ]"
                    + "\nEMail [ castte@163.com ]";

            Encode.buildQRCode(content, "target", "二维码.png", ImageType.PNG);
            Encode.buildQRCode(300, "http://www.baidu.com", "target", "二维码2.png", ImageType.PNG);
            Encode.buildQRCode(content, new FileOutputStream(new File("d:/a.png")), ImageType.PNG);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
